package www.my.imageframecompare.okhttpDwonload;

import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.CertificatePinner;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by ${张英杰} on 2018/8/7.
 */

public class OKHttpUtils {
    private static OKHttpUtils sInstance;
    private static final OkHttpClient mOkHttpClient = new OkHttpClient();
    //请求类型
    public static final MediaType mJSON = MediaType.parse("application/json; charset=utf-8");

    private OKHttpUtils() {
        /**
         * 设置连接超时时间为40s
         */
        mOkHttpClient.newBuilder().connectTimeout(40, TimeUnit.SECONDS);
        /**
         * 读取超时时间
         */
        mOkHttpClient.newBuilder().readTimeout(60, TimeUnit.SECONDS);
        /**
         * 写入超时时间
         */
        mOkHttpClient.newBuilder().writeTimeout(60, TimeUnit.SECONDS);
//        /**
//         * 证书验证
//         */
//        mOkHttpClient.newBuilder().certificatePinner(new CertificatePinner
//                .Builder()
//                .add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
//                .build()).build();
    }

    /**
     * 单例模式
     *
     * @return
     */
    public static OKHttpUtils instance() {
        if (sInstance == null) {
            synchronized (OKHttpUtils.class) {
                if (sInstance == null) {
                    sInstance = new OKHttpUtils();
                }
            }
        }
        return sInstance;
    }

    /**
     * 这是一个get请求拼接请求路径的方法
     *
     * @param requestPacket
     * @return
     */
    private static String appendUrl(RequestPacket requestPacket) {
        return requestPacket.url + "?" + appendArguments(requestPacket);
    }

    /**
     * 这是一个拼接get请求请求参数的方法
     *
     * @param requestPacket
     * @return
     */
    private static String appendArguments(RequestPacket requestPacket) {
        String argument = "";
        for (String key : requestPacket.arguments.keySet()) {
            if (requestPacket.getArgument(key) != null) {
                if (argument.equals("")) {
                    argument = key + "=" + requestPacket.getArgument(key);
                } else {
                    argument = argument + "&" + key + "=" + requestPacket.getArgument(key);
                }
            }
        }
        return argument;
    }

    private static final String TAG = "OKHttpUtils";
    /**
     * 这是一个下载文件的方法
     *
     * @param filepath                 文件路径
     * @param filename                 文件名字
     * @param donwloadResponseListener 回调监听
     */
//    public void donwloadFile(final String filepath, RequestPacket requestPacket, final String filename, final DonwloadResponseListener donwloadResponseListener) {
    public void donwloadFile(final String filepath, String url, final String filename, final DonwloadResponseListener donwloadResponseListener) {
        Request request = null;
        Request.Builder builder = new Request.Builder();
//        request = builder.url(appendUrl(requestPacket)).build();
        request = builder.url(url).build();
//        Log.d("下载文件的路径", appendUrl(requestPacket));
        Log.d("下载文件的路径", url);
        //发送异步请求
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG,"download failure FFFFFF");
                e.printStackTrace();
                donwloadResponseListener.onfailure();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() < 200 || response.code() >= 300) {
                    Log.i(TAG,"download failure response.code =="+response.code());
                    donwloadResponseListener.onfailure();
                }
                //将返回结果转化为流，并写入文件
                int len;
                byte[] buf = new byte[1024];
                InputStream inputStream = response.body().byteStream();
                /**
                 * 写入本地文件
                 */
//                String responseFileName = getHeaderFileName(response);
                File file = null;
                file = new File(filepath +File.separator+ filename);
                Log.i(TAG,"file.exists && file.length =="+file.length());
                if (file.exists()&&file.length()>0){
                    file.delete();
                }
                /**
                 *如果服务器没有返回的话,使用自定义的文件名字
                 */
//                if (TextUtils.isEmpty(responseFileName)) {
//                    file = new File(filepath +File.separator+ filename);
//                    Log.i(TAG,"file.exists && file.length =="+file.length());
//                    while (file.exists()&&file.length()>0){
//                        Log.i(TAG,"file.exists && file.length =="+file.length());
//                        file = new File(filepath +File.separator+new Random(100)+ filename);
//                    }
//
//                } else {
//                    file = new File(filepath +File.separator+ responseFileName);
//                    while (file.exists()&&file.length()>0){
//                        Log.i(TAG,"file.exists && file.length =="+file.length());
//                        file = new File(filepath +File.separator+new Random(100)+ responseFileName);
//                    }
//                }
                Log.i("localFile===",file.toString());
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                while ((len = inputStream.read(buf)) != -1) {
                    fileOutputStream.write(buf, 0, len);
                }
                if (response.code() >= 200 && response.code()< 300) {
                    donwloadResponseListener.onSuccess(file);
                }
                fileOutputStream.flush();
                fileOutputStream.close();
                inputStream.close();
            }

        });
    }

    /**
     * 解析文件头
     * Content-Disposition:attachment;filename=FileName.txt
     * Content-Disposition: attachment; filename*="UTF-8''%E6%9B%BF%E6%8D%A2%E5%AE%9E%E9%AA%8C%E6%8A%A5%E5%91%8A.pdf"
     */
    private static String getHeaderFileName(Response response) {
        String dispositionHeader = response.header("Content-Disposition");
        if (!TextUtils.isEmpty(dispositionHeader)) {
            dispositionHeader.replace("attachment;filename=", "");
            dispositionHeader.replace("filename*=utf-8", "");
            String[] strings = dispositionHeader.split("; ");
            if (strings.length > 1) {
                dispositionHeader = strings[1].replace("filename=", "");
                dispositionHeader = dispositionHeader.replace("\"", "");
                return dispositionHeader;
            }
            return "";
        }
        return "";
    }
}
